package com.saguitech.sgemeos.ui.activities;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.ExecutionException;

import android.app.Activity;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.Intent;
import android.graphics.Typeface;
import android.os.AsyncTask;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.Button;
import android.widget.ListView;
import android.widget.SimpleAdapter;

import com.saguitech.sgemeos.R;
import com.saguitech.sgemeos.business.LoginBusiness;
import com.saguitech.sgemeos.business.ParticipantBusiness;
import com.saguitech.sgemeos.services.ParticipationService;
import com.saguitech.sgemeos.utils.IsNetworkAvailable;
import com.saguitech.sgemeos.utils.MenuBase;
import com.saguitech.sgemeos.utils.MenuBase.TargetActivity;

/**
 * Activity para ver os dados do perfil de usuário
 * 
 * @author eduardo.seabra@saguitech.com.br
 * 
 */
public class ProfileActivity extends Activity {

	LoginBusiness login;
	ParticipantBusiness profile;
	ParticipationService service;

	String yes;
	String no;

	List<Map<String, String>> list = new ArrayList<Map<String, String>>();

	Button mainButton;

	ListView lv;

	SimpleAdapter adapter;

	Intent it;

	String[] from = { "name", "cpf", "birthdate", "gender", "adress", "city",
			"state", "cep", "telephone", "cellphone", "login", "email",
			"confirmed", "student" };
	int[] to = { R.id.profileNameText, R.id.profileCPFText,
			R.id.profileBirthDateText, R.id.profileGenderText,
			R.id.profileAddressText, R.id.profileCityText,
			R.id.profileStateText, R.id.profileCEPText,
			R.id.profileTelephoneText, R.id.profileCellphoneText,
			R.id.profileLoginText, R.id.profileEmailText,
			R.id.profileConfirmedText, R.id.profileStudentText };

	/** Called when the activity is first created. */
	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.profile);

		Button mainButton = (Button) findViewById(R.id.btnapp);
		Typeface font = Typeface.createFromAsset(getAssets(),
				"fonts/GOODTIME.ttf");
		mainButton.setTypeface(font);

		login = (LoginBusiness) getIntent().getSerializableExtra("login");

		yes = getString(R.string.yes);
		no = getString(R.string.no);

		ListView lv = (ListView) findViewById(R.id.profileList);
		adapter = new SimpleAdapter(ProfileActivity.this, list,
				R.layout.profilerow, from, to);
		lv.setAdapter(adapter);
		
		refreshData();

	}

	private void refreshData() {
		try {
			AsyncTask<Context, Void, Boolean> internetAvailable = (new IsNetworkAvailable()).execute(ProfileActivity.this);
			if(internetAvailable.get())
				(new FetchDataTask()).execute(login.getUsername());
		} catch (InterruptedException e) {
			e.printStackTrace();
		} catch (ExecutionException e) {
			e.printStackTrace();
		}
	}

	/**
	 * Carrega os dados do perfil na lista do Adapter.
	 */
	private void setData() {
		list.clear();
		Map<String, String> map = new HashMap<String, String>();
		map.put("name", profile.getName());
		map.put("cpf", profile.getCpf());
		map.put("birthdate", profile.getBirthDate());
		map.put("gender", profile.getGender());
		map.put("adress", profile.getAddress());
		map.put("city", profile.getCity());
		map.put("state", profile.getState());
		map.put("cep", profile.getCep());
		map.put("telephone", profile.getTelephone());
		map.put("cellphone", profile.getCellphone());
		map.put("login", profile.getLogin());
		map.put("email", profile.getEmail());
		map.put("confirmed", (profile.isConfirmed() ? yes : no));
		map.put("student", (profile.isStudent() ? yes : no));
		list.add(map);
	}

	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		getMenuInflater().inflate(MenuBase.getLayoutResource(), menu);
		return true;
	}

	@Override
	public boolean onPrepareOptionsMenu(Menu menu) {
		MenuBase.adjustMenu(TargetActivity.PROFILE, menu);
		return true;
	}

	@Override
	public boolean onOptionsItemSelected(MenuItem item) {
		MenuBase.onItemSelected(ProfileActivity.this, item);
		if (MenuBase.isIntentPrepared()) {
			MenuBase.getIntent().putExtra("login", login);
			MenuBase.commitIntent(ProfileActivity.this);
		}
		return true;
	}

	public void onMenuButtonClick(View view) {
		it = new Intent(ProfileActivity.this, ApplicationActivity.class);
		it.putExtra("login", login);
		it.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
		startActivity(it);
	}

	public void onRefreshButtonClick(View view) {
		refreshData();
	}

	private class FetchDataTask extends
			AsyncTask<String, Void, ParticipantBusiness> {

		private ProgressDialog progress;

		@Override
		protected void onPreExecute() {
			progress = ProgressDialog.show(ProfileActivity.this, "",
					getText(R.string.loadMessage).toString());
		}

		@Override
		protected ParticipantBusiness doInBackground(String... params) {
			service = new ParticipationService();
			return service.getParticipantLogin(params[0]);
		}

		@Override
		protected void onPostExecute(ParticipantBusiness result) {
			profile = result;
			setData();
			adapter.notifyDataSetChanged();
			progress.dismiss();
		}
	};
}
